package com.example.provider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;

public class MyProvider extends ContentProvider {

	MyHelper helper;
	private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
	private static final String PATH="com.example.provider.share";
	static {
		matcher.addURI(PATH, "user", 1);
		matcher.addURI(PATH, "teacher", 2);
	}

	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
		helper = new MyHelper(getContext());
		return true;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		SQLiteDatabase sd= helper.getReadableDatabase();
		int delete=0;
		switch(matcher.match(uri)){
		case 1:
			 delete = sd.delete("user", null, null);
			break;
		case 2:
			delete=sd.delete("teacher", null, null);
		}
		return delete;
	}

	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		SQLiteDatabase sd= helper.getReadableDatabase();
		switch(matcher.match(uri)){
		case 1:
			return "vnd.android.cursor.dir/vnd.com.example.proider.user";
			}
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		// TODO Auto-generated method stub
		SQLiteDatabase sd= helper.getReadableDatabase();
		Uri uris=null;
		switch (matcher.match(uri)) {
		case 1:
			long studentid = sd.insert("user", null, values);
			uris=Uri.parse("content://"+PATH+"/user/"+studentid);
			break;
		case 2:
			long teacherid = sd.insert("user", null, values);
			uris=Uri.parse("content://"+PATH+"/teacher/"+teacherid);
		default:
			break;
		}
		return uris;
	}

	@Override
	public Cursor query(Uri uri, 
			String[] projection,
			String selection,
			String[] selectionArgs, 
			String sortOrder) {
		// TODO Auto-generated method stub
		Cursor cursor = null;
		SQLiteDatabase sd= helper.getReadableDatabase();
		switch (matcher.match(uri)) {
		case 1:
			cursor = sd.query("user", null, null, null, null, null, null);
			break;
		case 2:
			cursor=sd.query("teacher", null, null, null, null, null, null);
		default:
			break;
		}
		return cursor;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		// TODO Auto-generated method stub
		SQLiteDatabase sd= helper.getReadableDatabase();
		Uri updatauri=null;
		int updataid=0;
		switch (matcher.match(uri)) {
		case 1:
			updataid= sd.update("user", values, null, null);
			updatauri=Uri.parse("content://"+PATH+"/user/"+updataid);
			break;
		case 2:
			updataid = sd.update("teacher", values, null, null);
			updatauri=Uri.parse("content://"+PATH+"/teacher/"+updataid);
			break;
		default:
			break;
		}
		return updataid;
	}

}
